package com.lechi.web.job;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.lechi.web.common.utils.DateUtils;
import com.lechi.web.common.utils.StringUtils;
import com.lechi.web.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.net.ftp.FTPClient;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.util.ObjectUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type Get sensor data job.
 *
 * @author yangguang
 */
@Slf4j
public class GetSensorDataJob implements Job {

    /**
     * The constant map.
     */
    public static final Map<String, String> map = new HashMap<>();

    /**
     * Instantiates a new Get sensor data job.
     */
    public GetSensorDataJob() {


        map.put("4780088", "风向");
        map.put("4780089", "风向");
        map.put("4780090", "温度");
        map.put("4780091", "湿度");
        map.put("4780092", "气压");
        map.put("4780105", "分钟雨量");
        map.put("4780106", "小时雨量");
        map.put("4780107", "24小时雨量");
        map.put("4780093", "雨量");
        map.put("4780094", "紫外线");
        map.put("4780095", "温湿压-温度");
        map.put("4780096", "温湿压-湿度");
        map.put("4780097", "温湿压-气压");
        map.put("4780098", "机械式风速");
        map.put("4780099", "机械式风向");
        map.put("4780100", "雨量");
        map.put("4780101", "空气质量-PM1");
        map.put("4780102", "空气质量-PM2.5");
        map.put("4780103", "空气质量-PM10");
        map.put("unit_4780089", "°");
        map.put("unit_4780099", "°");
        map.put("unit_4780101", "ug/m³");
        map.put("unit_4780102", "ug/m³");
        map.put("unit_4780103", "ug/m³");
        map.put("unit_4780094", "W/㎡");

        map.put("3934181", "控制柜-电压");
        map.put("3934182", "控制柜-温度");
        map.put("3934183", "控制柜-门锁状态");
        map.put("3877229", "150厘米空气温度");
        map.put("3877232", "150厘米空气湿度");
        map.put("3877230", "40厘米空气温度");
        map.put("3877233", "40厘米空气湿度");
        map.put("3877231", "10厘米空气温度");
        map.put("3877234", "10厘米空气湿度");
        map.put("3877235", "二维超声-风速");
        map.put("3877236", "二维超声-风向");
        map.put("3877237", "光学雨量-分钟雨量");
        map.put("3877238", "光学雨量-小时雨量");
        map.put("3877239", "光学雨量-24小时雨量");
        map.put("3877240", "光学雨量-累计雨量");
        map.put("3877241", "翻斗雨量");
        map.put("3838178", "冠层温度");
        map.put("3877242", "冠层高度");
        map.put("3877276", "土壤PH-温度");
        map.put("3877277", "土壤PH");
        map.put("3877278", "土壤氧化还原");
        map.put("3838265", "总辐射辐照度");
        map.put("4137177", "土壤氮含量");
        map.put("4137178", "土壤磷含量");
        map.put("4137179", "土壤钾含量");
        map.put("4173331", "色温");
        map.put("4173332", "照度");
        map.put("4173333", "光合有效辐射");
        map.put("4173334", "光合光子通量密度");
        map.put("4173335", "有效光量密度");
        map.put("4173336", "蓝-紫 辐射照度");
        map.put("4173337", "黄-绿 辐射照度");
        map.put("4173338", "红-橙 辐射照度");
        map.put("4173339", "红蓝辐射照度比");
        map.put("4173340", "光合辐射照度");
        map.put("4173341", "通量密度与照度转换");
        map.put("4173342", "叶绿素a");
        map.put("4173343", "叶绿素b");
        map.put("4173345", "土壤5cm-体积含水率");
        map.put("4173344", "土壤5cm-温度");
        map.put("4173347", "土壤10cm-体积含水率");
        map.put("4173346", "土壤10cm-温度");
        map.put("4173349", "土壤20cm-体积含水率");
        map.put("4173348", "土壤20cm-温度");
        map.put("4173351", "土壤30cm-体积含水率");
        map.put("4173350", "土壤30cm-温度");
        map.put("4173353", "土壤40cm-体积含水率");
        map.put("4173352", "土壤40cm-温度");
        map.put("4302536", "土壤50cm-体积含水率");
        map.put("4302537", "土壤50cm-温度");
        map.put("4196855", "控制柜-电压");
        map.put("4196856", "控制柜-温度");
        map.put("4196857", "控制柜-门锁状态");
        map.put("4196858", "150厘米空气温度");
        map.put("4196859", "150厘米空气湿度");
        map.put("4196860", "40厘米空气温度");
        map.put("4196861", "40厘米空气湿度");
        map.put("4196862", "10厘米空气温度");
        map.put("4196863", "10厘米空气湿度");
        map.put("4196864", "二维超声-风速");
        map.put("4196865", "二维超声-风向");
        map.put("4196866", "光学雨量-分钟雨量");
        map.put("4196867", "光学雨量-小时雨量");
        map.put("4196868", "光学雨量-24小时雨量");
        map.put("4196869", "光学雨量-累计雨量");
        map.put("4196870", "翻斗雨量");
        map.put("4196871", "冠层温度");
        map.put("4196872", "冠层高度");
        map.put("4196873", "土壤PH-温度");
        map.put("4196874", "土壤PH");
        map.put("4196875", "土壤氧化还原");
        map.put("4196876", "总辐射传感器");
        map.put("4196877", "土壤氮含量");
        map.put("4196878", "土壤磷含量");
        map.put("4196879", "土壤钾含量");
        map.put("4196880", "色温");
        map.put("4196881", "照度");
        map.put("4196882", "光合有效辐射");
        map.put("4196883", "光合光子通量密度");
        map.put("4196884", "有效光量密度");
        map.put("4196885", "蓝-紫 辐射照度");
        map.put("4196886", "黄-绿 辐射照度");
        map.put("4196887", "红-橙 辐射照度");
        map.put("4196888", "红蓝辐射照度比");
        map.put("4196889", "光合辐射照度");
        map.put("4196890", "通量密度与照度转换");
        map.put("4196891", "叶绿素a");
        map.put("4196892", "叶绿素b");
        map.put("4196894", "土壤5cm-体积含水率");
        map.put("4196893", "土壤5cm-温度");
        map.put("4196896", "土壤10cm-体积含水率");
        map.put("4196895", "土壤10cm-温度");
        map.put("4196898", "土壤20cm-体积含水率");
        map.put("4196897", "土壤20cm-温度");
        map.put("4196900", "土壤30cm-体积含水率");
        map.put("4196899", "土壤30cm-温度");
        map.put("4196902", "土壤40cm-体积含水率");
        map.put("4196901", "土壤40cm-温度");
        map.put("4290866", "土壤50cm-体积含水率");
        map.put("4290867", "土壤50cm-温度");


        map.put("unit_4196860", "°C");
        map.put("unit_3877232", "°C");
        map.put("unit_3877233", "°C");
        map.put("unit_3877242", "°C");
        map.put("unit_4196872", "cm");
        map.put("unit_4173345", "m³/m³");
        map.put("unit_4173347", "m³/m³");
        map.put("unit_4173349", "m³/m³");
        map.put("unit_4173351", "m³/m³");
        map.put("unit_4173353", "m³/m³");
        map.put("unit_4196855", "°C");
        map.put("unit_4196856", "°C");
        map.put("unit_4196894", "°C");
        map.put("unit_4196896", "°C");
        map.put("unit_4196858", "°C");
        map.put("unit_4196862", "°C");
        map.put("unit_4196871", "°C");
        map.put("unit_4196873", "°C");
        map.put("unit_4196898", "°C");
        map.put("unit_4196900", "°C");
        map.put("unit_4196902", "°C");
        map.put("unit_4196893", "°C");
        map.put("unit_4196895", "°C");
        map.put("unit_4196897", "°C");
        map.put("unit_4196899", "°C");
        map.put("unit_4196901", "°C");
        map.put("unit_4290867", "°C");
        map.put("unit_3877235", "°");
        map.put("unit_4196865", "°");
        map.put("unit_4196857", "");
        map.put("unit_4196884", "umol/m²/s");
        map.put("unit_4196874", "Mol ·L -1");
        map.put("unit_3877277", "Mol ·L -1");
        map.put("unit_4196885", "w/m²");
        map.put("unit_4196883", "w/m²");
        map.put("unit_4196886", "w/m²");
        map.put("unit_4196891", "w/m²");
        map.put("unit_4196887", "w/m²");
        map.put("unit_4196889", "w/m²");
        map.put("unit_4196892", "w/m²");
        map.put("unit_4196882", "w/m²");
        map.put("unit_4196890", "umol/m²/s/Klx");
        map.put("unit_4302536", "m³/m³");

        map.put("unit_3838265", "W/m²");
        map.put("unit_3877229", "°C");
        map.put("unit_3877230", "°C");
        map.put("unit_3877231", "°C");
        map.put("unit_3877236", "°");
        map.put("unit_3838178", "°C");
        map.put("unit_3877276", "°C");
        map.put("unit_3934182", "°C");
        map.put("unit_4173344", "°C");
        map.put("unit_4173346", "°C");
        map.put("unit_4173348", "°C");
        map.put("unit_4173350", "°C");
        map.put("unit_4173352", "°C");
        map.put("unit_4302537", "°C");
        map.put("unit_3934183", "");
        map.put("unit_4173333", "w/m²");
        map.put("unit_4173334", "umol/m²/s");
        map.put("unit_4173335", "umol/m²/s");
        map.put("unit_4173336", "w/m²");
        map.put("unit_4173337", "w/m²");
        map.put("unit_4173338", "w/m²");
        map.put("unit_4173340", "w/m²");
        map.put("unit_4173341", "umol/m²/s");
        map.put("unit_4173342", "w/m²");
        map.put("unit_4173343", "w/m²");

        map.put("3934181_1min", "控制柜-电压");
        map.put("3934182_1min", "控制柜-温度");
        map.put("3934183_1min", "控制柜-门锁状态");
        map.put("3877229_1min", "150厘米空气温度");
        map.put("3877232_1min", "150厘米空气湿度");
        map.put("3877230_1min", "40厘米空气温度");
        map.put("3877233_1min", "40厘米空气湿度");
        map.put("3877231_1min", "10厘米空气温度");
        map.put("3877234_1min", "10厘米空气湿度");
        map.put("3877235_1min", "二维超声-风速");
        map.put("3877236_1min", "二维超声-风向");
        map.put("3877237_1min", "光学雨量-分钟雨量");
        map.put("3877238_60min", "光学雨量-小时雨量");
        map.put("3877239_24hour", "光学雨量-24小时雨量");
        map.put("3877240_1min", "光学雨量-累计雨量");
        map.put("3877241_1min", "翻斗雨量");
        map.put("3838178_10min", "冠层温度");
        map.put("3877242_24hour", "冠层高度");
        map.put("3877276_60min", "土壤PH-温度");
        map.put("3877277_60min", "土壤PH");
        map.put("3877278_60min", "土壤氧化还原");
        map.put("3838265_1min", "总辐射传感器");
        map.put("4137177_60min", "土壤氮含量");
        map.put("4137178_60min", "土壤磷含量");
        map.put("4137179_60min", "土壤钾含量");
        map.put("4173331_10min", "色温");
        map.put("4173332_10min", "照度");
        map.put("4173333_10min", "光合有效辐射");
        map.put("4173334_10min", "光合光子通量密度");
        map.put("4173335_10min", "有效光量密度");
        map.put("4173336_10min", "蓝-紫 辐射照度");
        map.put("4173337_10min", "黄-绿 辐射照度");
        map.put("4173338_10min", "红-橙 辐射照度");
        map.put("4173339_10min", "红蓝辐射照度比");
        map.put("4173340_10min", "光合辐射照度");
        map.put("4173341_10min", "通量密度与照度转换");
        map.put("4173342_10min", "叶绿素a");
        map.put("4173343_10min", "叶绿素b");
        map.put("4173345_60min", "土壤5cm-体积含水率");
        map.put("4173344_60min", "土壤5cm-温度");
        map.put("4173347_60min", "土壤10cm-体积含水率");
        map.put("4173346_60min", "土壤10cm-温度");
        map.put("4173349_60min", "土壤20cm-体积含水率");
        map.put("4173348_60min", "土壤20cm-温度");
        map.put("4173351_60min", "土壤30cm-体积含水率");
        map.put("4173350_60min", "土壤30cm-温度");
        map.put("4173353_60min", "土壤40cm-体积含水率");
        map.put("4173352_60min", "土壤40cm-温度");
        map.put("4302536_60min", "土壤50cm-体积含水率");
        map.put("4302537_60min", "土壤50cm-温度");
        map.put("4196855_1min", "控制柜-电压");
        map.put("4196856_1min", "控制柜-温度");
        map.put("4196857_1min", "控制柜-门锁状态");
        map.put("4196858_1min", "150厘米空气温度");
        map.put("4196859_1min", "150厘米空气湿度");
        map.put("4196860_1min", "40厘米空气温度");
        map.put("4196861_1min", "40厘米空气湿度");
        map.put("4196862_1min", "10厘米空气温度");
        map.put("4196863_1min", "10厘米空气湿度");
        map.put("4196864_1min", "二维超声-风速");
        map.put("4196865_1min", "二维超声-风向");
        map.put("4196866_1min", "光学雨量-分钟雨量");
        map.put("4196867_60min", "光学雨量-小时雨量");
        map.put("4196868_24hour", "光学雨量-24小时雨量");
        map.put("4196869_10min", "光学雨量-累计雨量");
        map.put("4196870_10min", "翻斗雨量");
        map.put("4196871_10min", "冠层温度");
        map.put("4196872_24hour", "冠层高度");
        map.put("4196873_10min", "土壤PH-温度");
        map.put("4196874_10min", "土壤PH");
        map.put("4196875_10min", "土壤氧化还原");
        map.put("4196876_10min", "总辐射传感器");
        map.put("4196877_10min", "土壤氮含量");
        map.put("4196878_10min", "土壤磷含量");
        map.put("4196879_10min", "土壤钾含量");

        map.put("4196880_10min", "色温");
        map.put("4196881_10min", "照度");
        map.put("4196882_10min", "光合有效辐射");
        map.put("4196883_10min", "光合光子通量密度");
        map.put("4196884_10min", "有效光量密度");
        map.put("4196885_10min", "蓝-紫 辐射照度");
        map.put("4196886_10min", "黄-绿 辐射照度");
        map.put("4196887_10min", "红-橙 辐射照度");
        map.put("4196888_10min", "红蓝辐射照度比");
        map.put("4196889_10min", "光合辐射照度");
        map.put("4196890_10min", "通量密度与照度转换");
        map.put("4196891_10min", "叶绿素a");
        map.put("4196892_10min", "叶绿素b");
        map.put("4196894_60min", "土壤5cm-体积含水率");
        map.put("4196893_60min", "土壤5cm-温度");
        map.put("4196896_60min", "土壤10cm-体积含水率");
        map.put("4196895_60min", "土壤10cm-温度");
        map.put("4196898_60min", "土壤20cm-体积含水率");
        map.put("4196897_60min", "土壤20cm-温度");
        map.put("4196900_60min", "土壤30cm-体积含水率");
        map.put("4196899_60min", "土壤30cm-温度");
        map.put("4196902_60min", "土壤40cm-体积含水率");
        map.put("4196901_60min", "土壤40cm-温度");
        map.put("4290866_60min", "土壤50cm-体积含水率");
        map.put("4290867_60min", "土壤50cm-温度");
    }

    @Override
    public void execute(JobExecutionContext context) {
        final String cron = context.getMergedJobDataMap().get("cron") + "";
        final String deviceLC002 = HttpUtils.sendSSLPost("https://www.dtuip.com/queryUserAllSensorDatas.htm", "userId=93065&deviceIds=275600");
        final JSONObject deviceJSON2 = JSON.parseObject(deviceLC002);
        if (deviceJSON2 == null) {
            return;
        }
        final JSONArray senLastDataList2 = deviceJSON2.getJSONArray("senLastDataList");
        if (!deviceLC002.isBlank() && !deviceJSON2.isEmpty()) {
            List<JSONObject> jsonObjectList2 = Lists.newArrayList();
            addJsonObject(cron, jsonObjectList2, senLastDataList2);
            uploadFtp("LC002", JSONObject.toJSONString(jsonObjectList2), cron);
        }

        final String deviceLC001 = HttpUtils.sendSSLPost("https://www.dtuip.com/queryUserAllSensorDatas.htm", "userId=93065&deviceIds=251835");
        final JSONObject deviceJSON1 = JSON.parseObject(deviceLC001);
        if (deviceJSON1 == null) {
            return;
        }
        final JSONArray senLastDataList1 = deviceJSON1.getJSONArray("senLastDataList");
        if (!deviceLC001.isBlank() && !deviceJSON1.isEmpty()) {
            List<JSONObject> jsonObjectList1 = new ArrayList<>();
            addJsonObject(cron, jsonObjectList1, senLastDataList1);
            uploadFtp("LC001", JSONObject.toJSONString(jsonObjectList1), cron);
        }
    }

    private void addJsonObject(String cron, List<JSONObject> jsonObjectList, JSONArray senLastDataList1) {
        senLastDataList1.forEach(sensor -> {
            JSONObject sensorObj = (JSONObject) sensor;
            JSONObject target = new JSONObject();
            final Object sensorId = sensorObj.get("sensorId");
            // 4291312最后计算时间的排除掉
            if (!"4291312".equals(sensorId) && !ObjectUtils.isEmpty(map.get(sensorId + "_" + cron))) {
                target.put("sensorId", sensorId);
                target.put("val", sensorObj.get("val"));
                target.put("unit", map.getOrDefault("unit_" + sensorId, String.valueOf(sensorObj.get("unit"))));
                target.put("name", map.get(sensorId));
                jsonObjectList.add(target);
            }
        });
    }

    /**
     * Upload ftp.
     *
     * @param address the address
     * @param content the content
     * @param cron    the cron
     */
    public void uploadFtp(String address, String content, String cron) {

        //创建基于FTP协议访问文件服务器的客户端对象
        final String filePath = StringUtils.format("{}/{}", address, DateUtils.datePath());
        final String fileName = StringUtils.format("{}_{}_{}.{}", address, DateUtils.getYYYYMMDDHHMMTime(), cron, "json");
        FTPClient ftpClient = new FTPClient();
        try {
            //连接ftp服务器并验证用户名密码
            ftpClient.connect("124.114.99.54", 1111);
            ftpClient.login("admin", "k%!yWuQoyMbEJ6ed");
            ftpClient.enterLocalPassiveMode();
            String[] dirs = filePath.split("/");
            String currentDir = "/";
            boolean success = ftpClient.changeWorkingDirectory(currentDir + filePath);
            if (!success) {
                for (String dirName : dirs) {
                    if (!dirName.isEmpty()) {
                        currentDir += dirName + "/";
                        success = ftpClient.changeWorkingDirectory(currentDir);
                        if (!success) {
                            success = ftpClient.makeDirectory(dirName);
                            if (success) {
                                ftpClient.changeWorkingDirectory(dirName);
                            } else {
                                System.err.println("Failed to create directory: " + dirName);
                            }
                        }
                    }
                }
            }
            // 将字符串转换为字节数组
            byte[] bytes = content.getBytes();
            InputStream inputStream = new ByteArrayInputStream(bytes);
            ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
            boolean isStore = ftpClient.storeFile(fileName, inputStream);
//            System.err.println("文件上传成功？" + isStore + "===" + fileName);
            ftpClient.disconnect();
        } catch (Exception e) {
            log.error("文件上传ftp产生异常:", e);
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout(); // 登出
                    ftpClient.disconnect(); // 断开连接
                }
            } catch (IOException e) {
                log.error("ftpClient 关闭连接产生异常:", e);
            }
        }
    }
}